<template>
  <div class="homepages">
	 <headNavBar
	 	title="会员专区"
	 	:color="'#fff'"
	 	:size="15"
	 	:backShow="false"
	 	:background="'#ff4e22'"
		:backBtn="false"
	 />
	 <view class="calendar-container">
	 	<!-- 最新持仓数据展示 -->
	 	<view class="stock-data" v-if="latestStock">
	 		<text class="section-title">当前持仓</text>
	 		<view class="stock-item">
	 			<text class="stock-label">买入价格：</text>
	 			<text class="stock-value">{{ latestStock.price }}</text>
	 		</view>
	 		<view class="stock-item">
	 			<text class="stock-label">股票代码：</text>
	 			<text class="stock-value">{{ latestStock.code }}</text>
	 		</view>
	 		<view class="stock-item">
	 			<text class="stock-label">股票名称：</text>
	 			<text class="stock-value">{{ latestStock.name }}</text>
	 		</view>
	 		<view class="stock-item">
	 			<text class="stock-label">买入时间：</text>
	 			<text class="stock-value">{{ latestStock.createTime }}</text>
	 		</view>
	 	</view>
	 	<view class="section-divider"></view> <!-- 分割线 -->
	 	<view class="calendar-weekdays">
	 		<view class="calendar-weekday" v-for="(day, index) in workDays" :key="index">
	 			{{ day }}
	 		</view>
	 	</view>
	 	<view class="calendar-grid">
	 		<!-- 日历日期 -->
	 		<view class="calendar-day" v-for="(day, index) in filteredDaysInMonth" :key="index"
	 			:style="getDayStyle(day.profitRate)">
	 			<text class="day-number">{{ day.date }}</text>
	 			<text class="profit-rate" :style="getProfitStyle(day.profitRate)">
	 				{{ day.profitRate ? (day.profitRate > 0 ? `+${day.profitRate}%` : `${day.profitRate}%`) : '' }}
	 			</text>
	 		</view>
	 	</view>
	 	<view class="section-divider"></view> <!-- 分割线 -->
	 	<view class="total-profit">
	 		<text class="total-profit-title">{{ year }}年{{ month }}月总收益率：</text>
	 		<text :class="{'profit-positive': totalProfitRate > 0, 'profit-negative': totalProfitRate < 0}">
	 			{{ totalProfitRate }}%
	 		</text>
	 	</view>
	 </view>
  </div>
</template>

<script>
	import dayjs from 'dayjs';
	import {
		requestWithToken
	} from '@/utils/request.js';

	export default {
		data() {
			return {
				data: [],
				month: dayjs().month() + 1, // 当前月份
				year: dayjs().year(), // 当前年份
				daysInMonth: [],
				filteredDaysInMonth: [],
				totalProfitRate: 0,
				workDays: ["周一", "周二", "周三", "周四", "周五"],
				latestStock: {}, // 当前持仓数据
			};
		},
		mounted() {
			this.generateCalendar();
			this.getNewStockData();
		},
		methods: {
			async getNewStockData() {
				try {
					const res = await requestWithToken({
						url: "http://123.56.82.144:8090/stockData/getNewStockData",
						method: 'GET'
					});
					if (res.statusCode === 200) {
						this.latestStock = res.data.data;
						if (this.latestStock === null && res.data.status === 500 && res.data.message.includes(
								'积分不足')) {
							uni.redirectTo({
								url: '/pages/pointsError/pointsError' // 跳转到“积分不足”页面
							});
						}
					} else {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none',
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求失败',
						icon: 'none',
					});
				}
			},
			// 生成日历并请求数据
			async generateCalendar() {
				const startOfMonth = dayjs().month(this.month - 1).startOf('month');
				const endOfMonth = dayjs().month(this.month - 1).endOf('month');

				// 格式化为 YYYY-MM-DD
				const beginDate = startOfMonth.format('YYYY-MM-DD');
				const endDate = endOfMonth.format('YYYY-MM-DD');

				try {
					const res = await requestWithToken({
						url: "http://123.56.82.144:8090/stockData/getStockProfitData",
						method: 'GET',
						params: {
							beginDate,
							endDate
						}
					});
					if (res.statusCode === 200) {
						this.data = res.data.data;
						if (this.data === null && res.data.status === 500 && res.data.message.includes('积分不足')) {
							uni.redirectTo({
								url: '/pages/pointsError/pointsError' // 跳转到“积分不足”页面
							});
						}
					} else {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none',
						});
					}
				} catch (err) {
					uni.showToast({
						title: '请求失败',
						icon: 'none',
					});
				}
				if (this.data != null && this.data != undefined) {
					const numDaysInMonth = endOfMonth.date();
					const daysInMonth = [];

					let compoundProfit = 1; // 初始金额假设为1

					// 生成一个包含每一天日期的数组
					for (let i = 1; i <= numDaysInMonth; i++) {
						const currentDay = dayjs().month(this.month - 1).date(i).format('YYYY-MM-DD');
						const profitData = this.data.find(item => item.billDate === currentDay);
						const profitRate = profitData ? parseFloat(profitData.profitRate) : 0;

						// 复利计算：每一天的收益率累乘
						compoundProfit *= (1 + profitRate / 100);

						daysInMonth.push({
							date: i,
							profitRate: profitData ? profitData.profitRate : null,
						});
					}

					// 过滤掉周六和周日
					this.filteredDaysInMonth = daysInMonth.filter((day, index) => {
						const currentDay = dayjs().month(this.month - 1).date(day.date);
						return currentDay.day() !== 0 && currentDay.day() !== 6; // 排除周日和周六
					});

					this.daysInMonth = daysInMonth;

					// 计算总收益率（复利总收益率 - 1）
					this.totalProfitRate = ((compoundProfit - 1) * 100).toFixed(2);

					// 更新年份
					this.year = startOfMonth.year();
				}
			},

			// 切换到上一个月
			changeMonth(direction) {
				this.month += direction;

				// 处理月份溢出
				if (this.month < 1) {
					this.month = 12;
					this.year--;
				}

				this.generateCalendar(); // 重新生成日历并请求数据
			},

			getProfitStyle(profitRate) {
				if (!profitRate) return '';
				if (parseFloat(profitRate) > 0) {
					return 'color: red;';
				} else if (parseFloat(profitRate) < 0) {
					return 'color: green;';
				} else {
					return 'color: gray;';
				}
			},
			getDayStyle(profitRate) {
				if (!profitRate) return 'background-color: #ebebed'; // 绿色背景
				if (parseFloat(profitRate) > 0) {
					return 'background-color: rgb(255 217 217);'; // 红色背景
				} else if (parseFloat(profitRate) < 0) {
					return 'background-color: rgb(211 245 194)'; // 绿色背景
				}
			}
		}
	};
</script>

<style scoped>
	.calendar-container {
		padding: 20px;
		font-family: Arial, sans-serif;
	}

	.section-title {
		font-size: 18px;
		color: black;
		margin-bottom: 10px;
		color: #bcaaaa;
	}

	.stock-item {
		display: flex;
		justify-content: space-between;
		padding: 10px 0;
		/* 移除下面的线条 */
		border-bottom: none;
	}

	.stock-data {
		margin-bottom: 20px;
		font-size: 14px;
		color: #bcaaaa;
	}

	/* 容器样式 */
	.stock-data {
		display: flex;
		flex-direction: column;
		/* 垂直排列 */
		padding: 20px;
		border: 1px solid #ddd;
		/* 整体框架 */
		border-radius: 10px;
		/* 圆角 */
		background-color: #f9f9f9;
		/* 背景颜色 */
		width: 100%;
		/* 设置为100%宽度，方便响应式布局 */
		box-sizing: border-box;
		/* 包含边框和内边距 */
	}

	/* 单个项目的布局 */
	.stock-item {
		display: flex;
		justify-content: flex-start;
		/* 改为从左侧对齐 */
		margin-bottom: 12px;
		/* 每项之间的间隔 */
		padding: 10px;
		background-color: #fff;
		/* 每项的背景 */
		border: 1px solid #eee;
		/* 每项的边框 */
		border-radius: 5px;
		/* 每项圆角 */
	}

	/* 标签样式 */
	.stock-label {
		font-weight: bold;
		color: #bcaaaa;
		width: 100px;
		/* 为标签设置固定宽度 */
	}

	/* 值的样式 */
	.stock-value {
		color: #666;
		flex-grow: 1;
		/* 让值自适应宽度 */
		text-align: right;
		/* 值右对齐 */
	}

	/* 最后一项去掉底部边框 */
	.stock-item:last-child {
		margin-bottom: 0;
	}

	.calendar-header {
		justify-content: space-between;
		align-items: center;
		font-size: 18px;
		margin-bottom: 20px;
		padding: 10px 0;
	}

	.month-year {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.month {
		font-size: 16px;
		color: #555;
	}

	.month-button {
		background-color: #f6ebeb;
		color: #d99b9b;
		border: none;
		border-radius: 5px;
		cursor: pointer;
		font-size: 16px;
	}

	.month-button:hover {
		background-color: #f6ebeb;
	}

	.calendar-grid {
		display: grid;
		grid-template-columns: repeat(5, 1fr);
		/* 显示5天 */
		gap: 10px;
	}

	.calendar-weekdays {
		display: grid;
		grid-template-columns: repeat(5, 1fr);
		/* 显示5天 */
		text-align: center;
		margin-bottom: 10px;
	}

	.calendar-weekday {
		font-size: 13px;
		color: #bcaaaa;
	}

	.calendar-day {
		text-align: center;
		padding: 5px;
		border-radius: 5px;
		font-size: 14px;
		height: 30px;
		padding: 10px 0 20px;
	}

	.day-number {
		font-size: 16px;
		display: block;
	}

	.profit-rate {
		font-size: 14px;
		margin-top: 5px;
	}

	.total-profit {
		margin-top: 20px;
	}

	.total-profit-title {
		color: #bcaaaa;
	}

	/* 分割线样式 */
	.section-divider {
		height: 1px;
		background-color: #eaeaea;
		margin: 10px 0;
	}

	.profit-positive {
		color: #ff4d4f;
		/* 红色 */
	}

	.profit-negative {
		color: #52c41a;
		/* 绿色 */
	}
</style>